package springboot_cae.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import springboot_cae.entity.CaeEntity;
import springboot_cae.service.CaeService;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class UploadServlet {
	@Autowired  
    private HttpServletRequest request;
	@Autowired
	private CaeService caeService;
	
	//添加按钮的上传功能
    @GetMapping("/uploadAdd")
    public String uploadAdd() {
        return "uploadAdd";
    }
    @PostMapping("/uploadAdd")
    public String uploadAdd(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
        	request.setAttribute("message","上传失败，请重新选择文件！");
            return "messageAdd";
        }
        String fileName = file.getOriginalFilename();
        //String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
        //上面为项目内部相对路径，下面为绝对路径
        String filePath = "D://upload/";
        File dest = new File(filePath + fileName);
      //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){ 
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest);
            System.out.println("上传成功！路径为：");
            System.out.println(filePath+fileName);
            request.setAttribute("messageAdd",fileName);
            return "add";
        } catch (IOException e) {
        	request.setAttribute("message","上传失败，请重新选择文件！");
            return "message";
        }
    }
    //编辑按钮的上传功能
    @GetMapping("/uploadEdit")
    public String uploadEdit(@RequestParam(value = "id",required = true)int id) {
    	request.setAttribute("edit",id);
        return "uploadEdit";
    }
    @PostMapping("/uploadEdit")
    public String uploadEdit(@RequestParam("file") MultipartFile file,
    		@RequestParam(value = "id",required = true)int id,Model model) {
        if (file.isEmpty()) {
        	request.setAttribute("message","上传失败，请重新选择文件！");
        	request.setAttribute("id",id);
            return "messageEdit";
        }
        CaeEntity caeEntity=caeService.selectByService(id);
        String fileName = file.getOriginalFilename();
        String filePath = "D://upload/";
        File dest = new File(filePath + fileName);
      //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){ 
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest);
            System.out.println("上传成功！路径为：");
            System.out.println(filePath+fileName);
            request.setAttribute("messageEdit",fileName);
            caeEntity.setLicense(fileName);
            model.addAttribute("cae", caeEntity);
            return "edit";
        } catch (IOException e) {
        	request.setAttribute("message","上传失败，请重新选择文件！");
        	request.setAttribute("id",id);
            return "messageEdit";
        }
    }
    //下载功能
    @GetMapping("/download")
    public void testDownload(HttpServletResponse res,@RequestParam(value = "license",required = true) String fileName) {
      res.setHeader("content-type", "application/octet-stream");
      res.setContentType("application/octet-stream");
      res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
      byte[] buff = new byte[1024];
      BufferedInputStream bis = null;
      OutputStream os = null;
      try {
        os = res.getOutputStream();
      //bis = new BufferedInputStream(new FileInputStream(new File(request.getSession().getServletContext().getRealPath("/") + "upload/"+ fileName)));
        bis = new BufferedInputStream(new FileInputStream("D://upload/"+fileName));
        int i = bis.read(buff);
        while (i != -1) {
          os.write(buff, 0, buff.length);
          os.flush();
          i = bis.read(buff);
        }
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (bis != null) {
          try {
            bis.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
      System.out.println("success");
    }
}